package com.google.gwt.sample.dynatablerf.client.presenters;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.sample.dynatablerf.shared.GrifoRequestFactory;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.RequestContext;

public abstract class AbstractHasDataTabPresenter<E extends EntityProxy, T extends RequestContext>
		extends AbstractClosableTabPresenter<T> {

	private AsyncDataProvider<E> asyncDataProvider;

	public interface HasDataDiplay<E extends EntityProxy> extends
			ClosableTabDisplay {

		HasData<E> getData();
	}

	public AbstractHasDataTabPresenter(EventBus eventBus,
			GrifoRequestFactory requestFactory) {
		super(eventBus, requestFactory);

	}

	@Override
	protected void bind() {
		super.bind();

		asyncDataProvider = new AsyncDataProvider<E>() {

			@Override
			protected void onRangeChanged(HasData<E> display) {
				final Range range = display.getVisibleRange();
				final int start = range.getStart();
				final int length = range.getLength();
				fetch(start, length);
			}
		};
		asyncDataProvider.addDataDisplay(getHasDataDisplay().getData());
	}

	@Override
	protected ClosableTabDisplay getClosableTabDisplay() {
		return getHasDataDisplay();
	}

	protected abstract HasDataDiplay<E> getHasDataDisplay();

	protected abstract void fetch(final int start, int length);

	protected AsyncDataProvider<E> getAsyncDataProvider() {
		return asyncDataProvider;
	}

}
